package com.tim.library;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;

import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMOfflinePushInfo;
import com.tencent.qcloud.tim.tuiofflinepush.utils.TUIOfflinePushLog;
import com.tencent.qcloud.tuicore.TUILogin;

public class MessageNotification {

    private static final String TAG = MessageNotification.class.getSimpleName();

    private static final String NOTIFICATION_CHANNEL_ID = "IM_COMMON_SLG_NOTIFY_ID";
    private static final String NOTIFICATION_CHANNEL_NAME = "IM_COMMON_SLG_NOTIFY_NAME";

    private final NotificationManager mManager;

    private static MessageNotification INSTANCE;

    // 私有化构造函数
    private MessageNotification(Context context) {
        mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (mManager == null)
            TUIOfflinePushLog.e(TAG, "get NotificationManager failed");
        else
            createNotificationChannel();
    }

    /**
     * 获取单例对象
     */
    public static MessageNotification getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new MessageNotification(context.getApplicationContext());
        }
        return INSTANCE;
    }

    private static Ringtone mRingtone;

    public static synchronized void playSound(Uri uri) {
        if (mRingtone == null) {
            mRingtone = RingtoneManager.getRingtone(TUILogin.getAppContext(), uri);
        }
        if (!mRingtone.isPlaying()) {
            mRingtone = RingtoneManager.getRingtone(TUILogin.getAppContext(), uri);
            mRingtone.play();
        }
    }

    private void createNotificationChannel() {
        if (mManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            );

            channel.setSound(null, null);
            channel.enableVibration(true);
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            mManager.createNotificationChannel(channel);
        }
    }

    /**
     * 发送通知
     *
     * @param msg    消息类
     * @param resId  icon
     * @param launch 点击意图
     */
    @SuppressLint("UnspecifiedImmutableFlag")
    public void notify(V2TIMMessage msg, int resId, Intent launch) {
        if (msg == null
                || msg.getOfflinePushInfo() == null
                || msg.getOfflinePushInfo().getDesc() == null) return;

        if (mManager != null) {
            // 构建一个Notification构造器
            Notification.Builder builder;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                builder = new Notification.Builder(
                        TUILogin.getAppContext(),
                        NOTIFICATION_CHANNEL_ID
                );
            } else {
                builder = new Notification.Builder(TUILogin.getAppContext());
            }

            builder.setTicker("收到一条新消息")           //设置状态栏上的提示语
                    .setWhen(System.currentTimeMillis()) //设置该通知发生的时间
                    .setSmallIcon(resId)                 //设置状态栏内的小图标24X24
                    .setContentIntent(                   //设置点击跳转界面
                            PendingIntent.getActivity(
                                    TUILogin.getAppContext(),
                                    (int) SystemClock.uptimeMillis(),
                                    launch,
                                    PendingIntent.FLAG_UPDATE_CURRENT
                            )
                    )
                    .setLargeIcon(
                            BitmapFactory.decodeResource(
                                    TUILogin.getAppContext().getResources(),
                                    resId
                            )
                    );                                  //设置下拉列表中的图标(大图标)


            String title = null;
            String desc = null;
            V2TIMOfflinePushInfo v2TIMOfflinePushInfo = msg.getOfflinePushInfo();
            if (v2TIMOfflinePushInfo != null) {
                title = v2TIMOfflinePushInfo.getTitle();
                desc = v2TIMOfflinePushInfo.getDesc();
            }

            if (TextUtils.isEmpty(title)) {
                if (TextUtils.isEmpty(msg.getGroupID())) {
                    if (!TextUtils.isEmpty(msg.getFriendRemark())) {
                        title = msg.getFriendRemark();
                    } else if (!TextUtils.isEmpty(msg.getNickName())) {
                        title = msg.getNickName();
                    } else {
                        title = msg.getUserID();
                    }
                } else {
                    title = msg.getGroupID();
                }
            }
            builder.setContentTitle(title);
            builder.setContentText(desc);

            Notification notification = builder.build();         //获取构建好的Notification
            notification.defaults = Notification.DEFAULT_LIGHTS; //设置为默认的声音
            notification.flags |= Notification.FLAG_AUTO_CANCEL; //FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。

            mManager.notify((int) SystemClock.uptimeMillis(), notification);
        }
    }

    /**
     * 清除所有通知
     */
    public void clearAll() {
        if (mManager != null) {
            mManager.cancelAll();
        }
    }

}
